using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace XCommon.utils
{
    public class LogUtil
    {
        private static object _lockObject = new object();
        private static LogUtil _instance;

        private static string _defaultFileName = "bug.txt";

        public static LogUtil Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (_lockObject)
                    {
                        if (_instance == null)
                        {
                            _instance = new LogUtil();
                        }
                    }
                }
                return _instance;
            }
        }

        private string FileUrl
        {
            get
            {
                return IOUtil.JoinPath(AppDomain.CurrentDomain.BaseDirectory, "error\\[" + DateTime.Now.ToString("yyyyMMdd") + "]" + _defaultFileName);
            }
        }

        private LogUtil()
        {
            if (!ValidFileExists())
            {
                CreateFile();
            }
        }

        private bool ValidFileExists()
        {
            bool bRet = false;

            bRet = IOUtil.ExistsFile(FileUrl);

            return bRet;
        }

        private void CreateFile()
        {
            IOUtil.CreateFile(FileUrl, "File Create:" + DateTime.Now.ToString() + "", Encoding.UTF8);
        }

        public void WriteMessage(string msg)
        {
            lock (_lockObject)
            {
                using (StreamWriter writer = File.AppendText(FileUrl))
                {
                    writer.AutoFlush = false;
                    writer.Write(WriteHead() + msg);
                    writer.Flush();
                }
            }
        }

        private string WriteHead()
        {
            string tempHead = Environment.NewLine + "-----------------------[" + DateTime.Now.ToString() + "]--------------------------" + Environment.NewLine;
            return tempHead;
        }

        public static void Write(string msg)
        {
            LogUtil.Instance.WriteMessage(msg);
        }

        public static void WriteException(Exception ex)
        {
            LogUtil.Instance.WriteMessage("Type:" + ex.GetType().Name + ex.Message + Environment.NewLine + "At: " + ex.StackTrace + Environment.NewLine);
        }
    }
}
